--
-- Description: Script to save a locale.
-- This includes inserting a new record in the Locales table
-- if the Locale does not exist.
-- Returns the LocaleID.
-- Date created: 6 May 2008
--

set ANSI_NULLS on
set QUOTED_IDENTIFIER on
go

--
-- drop the procedure if it exists and recreate it.
--
if exists
(
	select * 
	from sys.objects
	where object_id = object_id(N'[dbo].[saveLocale_sp]')
	and type in (N'P', N'PC')
)

begin
    drop procedure [dbo]. [saveLocale_sp]
end
go

create procedure [dbo].[saveLocale_sp]
(
	@LocaleID smallint
    , @LocaleCode varchar(15)
	, @LocaleName nvarchar(400)
)
as
begin
	--
	-- validate the @LocaleID, @LocaleCode and @LocaleName. They cannot be null or empty.
	--
	if (@LocaleID is null)
	begin
		raiserror
		(
			N'@LocaleID parameter cannot be null or empty.'
			, 10 -- severity
			, 1 -- state
		)
	end
	
	if (@LocaleCode is null or LEN(@LocaleCode) = 0)
	begin
		raiserror
		(
			N'@LocaleCode parameter cannot be null or empty.'
			, 10 -- severity
			, 1 -- state
		)
	end
	
	if (@LocaleName is null or LEN(@LocaleName) = 0)
	begin
		raiserror
		(
			N'@LocaleName parameter cannot be null or empty.'
			, 10 -- severity
			, 1 -- state
		)
	end

	--
	-- check if the locale id, code and name exists in the table.
	--
	if not exists
	(
		select top 1 1
		from [dbo].[Locales]
		where LocaleID = @LocaleID
		and LocaleCode = @LocaleCode
		and LocaleName = @LocaleName
	)
	begin
		--
		-- create a new record with the new locale id, code and name.
		--
		insert into [dbo].[Locales]
		(
			LocaleID
			, LocaleCode
			, LocaleName
		)
		values
		(
			@LocaleID
			, @LocaleCode
			, @LocaleName
		)
	end

	--
	-- return the LocaleID back.
	--
	return @LocaleID
end
go

set ansi_nulls off
go
set quoted_identifier off
go
